package common

import (
	"bufio"
	"encoding/json"
	"log"
	"os"

	"github.com/tealeg/xlsx/v3"
)

// 处理hostinfo表格
func ParseHostInfo(sheet *xlsx.Sheet, fileName string) error {
	hostDist := make(map[string][]string)
	// 从第二行开始遍历（假设第一行是标题行）
	for rowNumber := 1; rowNumber < sheet.MaxRow; rowNumber++ {
		row, _ := sheet.Row(rowNumber)
		ip := row.GetCell(0).String()
		env := row.GetCell(1).String()
		hostType := row.GetCell(2).String()
		productInfo := row.GetCell(3).String()

		hostDist[ip] = []string{env, hostType, productInfo}
	}

	// 将hostDist序列化为JSON并写入文件
	if err := writeJSONToFile(hostDist, fileName); err != nil {
		log.Fatalf("ParseHostInfo Failed to write JSON to file: %v", err)
	}
	log.Printf("ParseHostInfo Success to write JSON to file: %v", hostDist)
	return nil
}

// 处理serviceinfo表格
func ParseServiceInfo(sheet *xlsx.Sheet, fileName string) error {
	serviceDist := make(map[string]map[string][]string)
	// 从第二行开始遍历（假设第一行是标题行）
	for rowNumber := 1; rowNumber < sheet.MaxRow; rowNumber++ {
		row, _ := sheet.Row(rowNumber)
		ip := row.GetCell(0).String()
		serviceName := row.GetCell(1).String()
		serviceType := row.GetCell(2).String()
		port := row.GetCell(3).String()
		env := row.GetCell(4).String()
		productInfo := row.GetCell(5).String()

		if _, exists := serviceDist[ip]; !exists {
			serviceDist[ip] = make(map[string][]string)
		}
		// 使用应用名称作为键
		serviceDist[ip][serviceName] = []string{serviceType, port, env, productInfo}
	}

	// 将serviceDist序列化为JSON并写入文件
	if err := writeJSONToFile(serviceDist, fileName); err != nil {
		log.Fatalf("ParseServiceInfo Failed to write JSON to file: %v", err)
	}
	log.Printf("ParseServiceInfo Success to write JSON to file: %v", serviceDist)
	return nil
}
func ParseServiceUrlInfo(sheet *xlsx.Sheet, fileName string) error {
	var serviceUrls []map[string]string

	// 从第二行开始遍历（假设第一行是标题行）
	for rowNumber := 1; rowNumber < sheet.MaxRow; rowNumber++ {
		row, _ := sheet.Row(rowNumber)
		serviceUrl := make(map[string]string)
		serviceUrl["nameInterface"] = row.GetCell(0).String()
		serviceUrl["urlInterface"] = row.GetCell(1).String()
		serviceUrl["requestMethod"] = row.GetCell(2).String()
		serviceUrl["serviceType"] = row.GetCell(3).String()
		serviceUrl["contentType"] = row.GetCell(4).String()
		serviceUrl["requestClientId"] = row.GetCell(5).String()
		serviceUrl["requestToken"] = row.GetCell(6).String()
		serviceUrl["requestBody"] = row.GetCell(7).String()
		serviceUrl["responseValue"] = row.GetCell(8).String()
		serviceUrl["env"] = row.GetCell(9).String()
		serviceUrl["businessCode"] = row.GetCell(10).String()

		serviceUrls = append(serviceUrls, serviceUrl)
	}

	// 将serviceUrls序列化为JSON并写入文件
	if err := writeJSONToFile(serviceUrls, fileName); err != nil {
		log.Fatalf("ParseServiceUrlInfo Failed to write JSON to file: %v", err)
	}
	log.Printf("ParseServiceUrlInfo Success to write JSON to file: %v", serviceUrls)
	return nil
}

// 将数据序列化为JSON并写入文件
func writeJSONToFile(data interface{}, fileName string) error {
	jsonData, err := json.MarshalIndent(data, "", "    ")
	if err != nil {
		return err // 直接返回错误，不再结束程序
	}

	file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		return err // 直接返回错误
	}
	defer file.Close()

	writer := bufio.NewWriter(file)
	if _, err := writer.Write(jsonData); err != nil {
		return err // 直接返回错误
	}
	if err := writer.Flush(); err != nil {
		return err // 返回 Flush 的错误
	}

	return nil // 成功完成，返回 nil
}
